package com.fancon.android.gardenjokesx.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import com.fancon.android.gardenjokesx.GardenJokesBaseActivity;
import com.fancon.android.gardenjokesx.entity.User;
import com.fancon.android.gardenjokesx.rpc.GardenJokesApiConnect;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.gardenjokesx.utils.UserUtil;

public class P01FromS06 extends GardenJokesBaseActivity {
	private Uri mImageCaptureUri;
	private Uri mImageCropUri;

	private static final int PICK_FROM_CAMERA = 1;
	private static final int CROP_FROM_CAMERA = 2;
	private static final int PICK_FROM_FILE = 3;
	User mUser = new User();
	Bundle bundle;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Intent intent = getIntent();
		if(getIntent().getExtras() != null){
			bundle = getIntent().getExtras();
		}
		if(getIntent().getExtras() != null && getIntent().getExtras().getSerializable("user") != null){
			mUser = (User) getIntent().getExtras().getSerializable("user");
		}
		int item = intent.getExtras().getInt("type", 0);
		Log.d("P01FromS06","type: "+item);
		Log.d("P01FronS06","screen_id: "+ bundle.getInt(Constant.SCREEN_ID));
		switch (item) {
		case PICK_FROM_CAMERA:
			doShot(PICK_FROM_CAMERA);
			break;
		case PICK_FROM_FILE:
			doShot(PICK_FROM_FILE);
		default:
			break;
		}
	}
	
	public Uri makeFilename(String prefix){
		String direct = "/meshtiles/avatar";
		
		File directory = new File(Environment.getExternalStorageDirectory() + direct);
		if (!directory.exists()) {
	        directory.mkdir();
	    }
		File file = new File(directory,prefix + String.valueOf(System.currentTimeMillis()) + ".jpg");
		return Uri.fromFile(file);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK)
			return;

		switch (requestCode) {
		case PICK_FROM_CAMERA:
			doCrop();
			break;

		case PICK_FROM_FILE:
			mImageCaptureUri = data.getData();
			if (mImageCaptureUri != null) {
				doCrop();
			}
			break;

		case CROP_FROM_CAMERA:

			File f = new File(mImageCaptureUri.getPath());

			if (f.exists()) {
				f.delete();
			}
			mUser.setUrl_image(mImageCropUri.getPath());
			
			Log.d("P01FronS06","screen_id: "+ bundle.getInt(Constant.SCREEN_ID));
			if(bundle.getInt(Constant.PRE_SCREEN_ID) == Constant.S01){
				Intent intent = new Intent(getApplicationContext(),
						SignupActivity.class);
				Bundle b = new Bundle();
				b.putSerializable("user", mUser);
				intent.putExtras(b);
				intent.putExtra("imagePath", mImageCropUri.getPath());
				Log.d("P01", mImageCropUri.getPath());
				startActivity(intent);
				finish();
			}
			if(bundle.getInt(Constant.PRE_SCREEN_ID) == Constant.U02){
				Bitmap bm = BitmapFactory.decodeFile(mImageCropUri.getPath());
				
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
    	        bm.compress(CompressFormat.JPEG, 100, bos);
    	        byte[] byteData = bos.toByteArray();
    	        ByteArrayBody bad = new ByteArrayBody(byteData, "avatar.jpg");
    	        MultipartEntity reqEntity = new MultipartEntity();
    	        String user_id = UserUtil.getInfoUserLogin(P01FromS06.this).getUser_id();
    	        try {
        	        reqEntity.addPart("image", bad);
					reqEntity.addPart("user_id",new StringBody(user_id));
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				//@binhbt-comment
				//Must change for enhance upload
    	        GardenJokesApiConnect apiConnect = new GardenJokesApiConnect(P01FromS06.this);
    	        String result = apiConnect.execPostImg(P01FromS06.this, GardenJokesApiConnect.GROUP_S, "updateImageProfile", reqEntity);
    	        Log.d("P01FromnS06","post result: "+ result);
    	        finish();
//    	        Intent intent = new Intent(P01FromS06.this,U02Activity.class);
//    	        startActivity(intent);
			}
			break;

		}
	}

	private void doCrop() {

		final ArrayList<P01CropOption> cropOptions = new ArrayList<P01CropOption>();

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setType("image/*");

		List<ResolveInfo> list = getPackageManager().queryIntentActivities(
				intent, 0);

		int size = list.size();

		if (size == 0) {
			Toast.makeText(this, "Can not find image crop app",
					Toast.LENGTH_SHORT).show();
			return;
		} else {
			mImageCropUri = makeFilename("tmp_avatar_cuted_");
			intent.setData(mImageCaptureUri);
			intent.putExtra("outputX", 72);
			intent.putExtra("outputY", 72);
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1);
			intent.putExtra("scale", true);
			intent.putExtra("output", mImageCropUri);
			intent.putExtra("return-data", false);

			if (size == 1) {
//				User mUser = new User();
//				if(getIntent().getExtras() != null && getIntent().getExtras().getSerializable("user") != null)
//					mUser = (User) getIntent().getExtras().getSerializable("user");
//				Bundle b = new Bundle();
//				b.putSerializable("user", mUser);
				Intent i = new Intent(intent);
//				i.putExtras(b);
				ResolveInfo res = list.get(0);

				i.setComponent(new ComponentName(res.activityInfo.packageName,
						res.activityInfo.name));

				startActivityForResult(i, CROP_FROM_CAMERA);
			} else {
				for (ResolveInfo res : list) {
					final P01CropOption co = new P01CropOption();

					co.title = getPackageManager().getApplicationLabel(
							res.activityInfo.applicationInfo);
					co.icon = getPackageManager().getApplicationIcon(
							res.activityInfo.applicationInfo);
					co.appIntent = new Intent(intent);

					co.appIntent
							.setComponent(new ComponentName(
									res.activityInfo.packageName,
									res.activityInfo.name));

					cropOptions.add(co);
				}

				P01CropOptionAdapter adapter = new P01CropOptionAdapter(
						getApplicationContext(), cropOptions);

				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle("Choose Crop App");
				builder.setAdapter(adapter,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int item) {
								startActivityForResult(
										cropOptions.get(item).appIntent,
										CROP_FROM_CAMERA);
							}
						});

				builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
					@Override
					public void onCancel(DialogInterface dialog) {

						if (mImageCaptureUri != null) {
							getContentResolver().delete(mImageCaptureUri, null,
									null);
							mImageCaptureUri = null;
						}
					}
				});

				AlertDialog alert = builder.create();

				alert.show();
			}
		}
	}

	public void doShot(int item) {
		// TODO Auto-generated method stub

		if (item == PICK_FROM_CAMERA) {
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

			mImageCaptureUri = makeFilename("tmp_avatar_");

			intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
					mImageCaptureUri);

			try {
				intent.putExtra("return-data", true);

				startActivityForResult(intent, PICK_FROM_CAMERA);
			} catch (ActivityNotFoundException e) {
				e.printStackTrace();
			}
		} else { // pick from file
			Intent intent = new Intent();

			intent.setType("image/*");
			intent.setAction(Intent.ACTION_GET_CONTENT);

			startActivityForResult(
					Intent.createChooser(intent, "Complete action using"),
					PICK_FROM_FILE);
		}
	}

}
